package cn.xxd.xxdwebsso.controller;

import cn.xxd.OrderServiceInterface;
import cn.xxd.common.UrlUtil;
import cn.xxd.common.UserUtil;
import cn.xxd.entity.LoginUser;
import cn.xxd.entity.OrdersItems;
import cn.xxd.entity.ReturnT;
import cn.xxd.entity.XxdAddress;
import cn.xxd.xxdssointerface.LoginService;
import cn.xxd.xxdssointerface.UserService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.regex.Pattern;

@Controller
public class UserController {

    @Reference(version = "1.0.0", timeout = 100000)
    private LoginService loginService;

    @Reference(version = "1.0.0", timeout = 100000)
    private UserService userService;

    @Reference(version = "1.0.0", timeout = 100000)
    private OrderServiceInterface orderService;


    @Value("${AUTHORITY}")
    private String AUTHORITY;

    @Value("${ORDER_URL}")
    private String ORDER_URL;

    @Value("${HOMEURL}")
    private String HOMEURL;


    @RequestMapping(value = "/user/address")
    public String address(LoginUser loginUser, Model model, HttpServletRequest request) {

        String id = null;
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(AUTHORITY)) {
                    id = cookie.getValue();
                }
            }
        }
        if (id != null) {
            String[] strings = id.split(":");
            if (strings[1] != null) {
                Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
                if (pattern.matcher(strings[1]).matches()) {
                    id = strings[1];
                } else {
                    return "login";
                }
            } else {
                return "login";
            }
        } else {
            return "login";
        }
        // 此处需要优化， 但暂时不做处理
        loginUser = loginService.getMsgById(id);
        String username = loginUser.getUsername();
        String name = loginUser.getName();
        if ("".equals(username)) {
            username = null;
        }
        if ("".equals(name)) {
            name = null;
        }
        LoginUser user = loginService.getMsg(username, name);
        String url = UrlUtil.getUrl(request);

        // 获取地址列表
        List<XxdAddress> list = userService.getAddressList(id);
        // 只显示3个地址
        if (list.size() > 3) {
            list = list.subList(0, 3);
        }


        model.addAttribute("user", user);
        model.addAttribute("url", url);
        model.addAttribute("list", list);
        model.addAttribute("HOMEURL", HOMEURL);
        return "address";
    }

    @RequestMapping(value = "/user/address/add", method = RequestMethod.POST)
    @ResponseBody
    public ReturnT addAddress(XxdAddress address, HttpServletRequest request) {
        String id = null;
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(AUTHORITY)) {
                    id = cookie.getValue();
                }
            }
        }
        if (id != null) {
            String[] strings = id.split(":");
            if (strings[1] != null) {
                Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
                if (pattern.matcher(strings[1]).matches()) {
                    address.setUserId(strings[1]);
                } else {
                    return new ReturnT(500, "用户未登录！");
                }
            } else {
                return new ReturnT(500, "用户未登录！");
            }
        } else {
            return new ReturnT(500, "用户未登录！");
        }
        return userService.addAddress(address);
    }

    @RequestMapping(value = "/user/address/edit", method = RequestMethod.POST)
    @ResponseBody
    public ReturnT editAddress(XxdAddress address, HttpServletRequest request) {
        String id = null;
        // 获取cookie
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(AUTHORITY)) {
                    id = cookie.getValue();
                }
            }
        }
        // 从cookie中获取shopUser的ID
        if (id != null) {
            String[] strings = id.split(":");
            if (strings[1] != null) {
                Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
                if (pattern.matcher(strings[1]).matches()) {
                    // 先置空string[1]的opt
                    int result = userService.changeStatus(strings[1]);
                    if (result > 0) {
                        // 根据id标记
                        userService.changeOpt(String.valueOf(address.getId()));
                    }
                } else {
                    return new ReturnT(500, "用户未登录！");
                }
            } else {
                return new ReturnT(500, "用户未登录！");
            }
        } else {
            return new ReturnT(500, "用户未登录！");
        }
        return new ReturnT(200, "success");
    }

    @PostMapping(value = "/user/address/del")
    @ResponseBody
    public ReturnT delAddress(String id) {
        int result = userService.delAddress(id);
        if (result > 0) {
            return new ReturnT(200, "success");
        }
        return new ReturnT(500, "删除失败！");
    }

    @RequestMapping(value = "/user/getOrder")
    public String getOrder(HttpServletRequest request, Model model) throws ParseException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String userId = UserUtil.getCurrentUserId(request, AUTHORITY);
        List<OrdersItems> list = orderService.queryOrdersItems(userId, null);
        for (OrdersItems o : list) {
            o.setCreateTime(dateFormat.parse(dateFormat.format(o.getCreateTime())));
        }
        model.addAttribute("list", list);
        model.addAttribute("url", ORDER_URL);
        model.addAttribute("HOMEURL", HOMEURL);
        return "order";
    }

    @PostMapping(value = "/user/delOrder")
    @ResponseBody
    public ReturnT delOrder(String id, HttpServletRequest request, Model model) throws ParseException {
        // 删除订单
        int result1 = orderService.delOrder(id);
        if (result1 <= 0) {
            return new ReturnT(500, "failed");
        }
        // 删除订单-商品 物理删除
        int result2 = orderService.deleteOrderItems(id);
        if (result2 <= 0) {
            return new ReturnT(500, "failed");
        }

        return new ReturnT(200, "success");
    }

    /**
     * 支付宝return_url
     */
    @RequestMapping(value = "/user/getOrderReturn")
    public String getOrderReturn(HttpServletRequest request, Model model) {
        String userId = UserUtil.getCurrentUserId(request, AUTHORITY);
        List<OrdersItems> list = orderService.queryOrdersItems(userId, null);
        model.addAttribute("list", list);
        model.addAttribute("url", ORDER_URL);
        model.addAttribute("HOMEURL", HOMEURL);
        return "order";
    }

}

